<template>
	<view class="view-contain">
		<public-module :title="title" />

		<!-- 日期和倒计时区域 -->
		<view class="date-countdown-container">
			<view class="current-date">{{ currentDate }}</view>
			<view class="exam-countdown">
				<text class="countdown-label">江苏省考倒计时约</text>
				<text class="countdown-value">{{ daysToExam }} 天</text>
			</view>
		</view>

		<!-- 公告栏和打卡按钮容器 -->
		<view class="announcement-punch-container">
			<view class="announcement-bar" @click="toggleAnnouncement">
				<view class="announcement-header">
					<view class="announcement-icon"><u-icon name="bell" color="#666666" size="18"></u-icon></view>
					<text class="announcement-title">{{noticeData.noticeTitle || '公告栏'}}</text>
					<view class="announcement-arrow"><u-icon :name="showAnnouncement ? 'arrow-up' : 'arrow-down'" color="#666666" size="18"></u-icon></view>
				</view>
				<view class="announcement-content" v-if="showAnnouncement">
					<rich-text :nodes="noticeData.noticeContent || '暂无公告内容'" class="announcement-text"></rich-text>
					<view class="announcement-footer"><text class="announcement-date">{{noticeData.updateTime || ''}}</text></view>
				</view>
			</view>

			<!-- 打卡按钮（与公告显隐联动） -->
			<view class="punch-btn-container" :style="{ display: showAnnouncement ? 'none' : 'flex' }">
				<view class="punch-btn" @click="navigateTo('mark')">
					<u-icon name="pushpin"  size="20" class="punch-icon"></u-icon>
					<text class="punch-text">今日打卡</text>
				</view>
			</view>
		</view>

		<!-- 主要内容区域（功能模块和排行榜） -->
		<view class="main-content-container">
			<!-- 顶部功能模块（横排展示，可左右滑动，一行四列） -->
			<view class="modules-container">
				<scroll-view class="modules-scroll" scroll-x="true" show-scrollbar="false" :scroll-with-animation="true">
					<view class="modules-row">
						<view class="module-card" hover-class="module-card-hover" @click="navigateTo(item.key)" v-for="item in allModules" :key="item.key">
							<view class="module-icon"><u-icon :name="item.icon" :color="item.color" size="32"></u-icon></view>
							<text class="module-title">{{ item.title }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 下方排行榜区域 -->
			<view class="rankings-container">

				<!-- 打卡排行榜 -->
				<view class="ranking-section">
					<view class="ranking-header">
						<view class="ranking-title-section">
							<view class="ranking-header-row">
								<text class="ranking-title" :class="{ 'star-animation': activeRankingIndex === 0 }">每日打卡榜</text>
								<!-- 身份类型标签 -->
								<view class="identity-tabs">
									<view class="identity-tab-item" :class="{ 'active': isPunchIdentityTabActive('在职') }" @click="switchPunchIdentityTab('在职')">
										在职
									</view>
									<view class="identity-tab-item" :class="{ 'active': isPunchIdentityTabActive('全职') }" @click="switchPunchIdentityTab('全职')">
										全职
									</view>
									<view class="identity-tab-item" :class="{ 'active': isPunchIdentityTabActive('应届') }" @click="switchPunchIdentityTab('应届')">
										应届
									</view>
								</view>
							</view>
							<!-- 排行榜标签切换 -->
							<view class="ranking-tabs">
								<view class="tab-item" :class="{ 'active': currentPunchTab === tab }" @click="switchPunchTab(tab)" v-for="tab in ['monthTotalMark','continuousMark','totalMark']" :key="tab">
									{{ tab === 'monthTotalMark' ? '本月累计' : tab === 'continuousMark' ? '历史连续' : '历史累计' }}
								</view>
							</view>
						</view>
					</view>
					<view class="ranking-list">
						<view class="ranking-item" v-for="(item, index) in (showAllPunchRankings ? punchRankings : punchRankings.slice(0,3))" :key="item.user_id">
							<view class="rank-number" :class="[
								index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : '',
								item.user_id === user.userId ? 'current-user' : ''
							]">{{ index + 1 }}</view>
							<view class="rank-username" :class="{ 'current-user': item.user_id === user.userId }">{{ item.userNickname }}</view>
							<view class="rank-score" :class="{ 'current-user': item.user_id === user.userId }">{{ item.total_mark_count }}天</view>
						</view>
						<view class="toggle-ranking" @click="showAllPunchRankings = !showAllPunchRankings" v-if="punchRankings.length > 3">
							<text>{{ showAllPunchRankings ? '收起' : '查看全部' }}</text>
							<u-icon :name="showAllPunchRankings ? 'arrow-up' : 'arrow-down'" color="#666666" size="14"></u-icon>
						</view>
					</view>
				</view>
				
				<!-- 模考击败榜 -->
				<view class="ranking-section">
					<view class="ranking-header">
						<view class="ranking-title-section">
							<text class="ranking-title" :class="{ 'star-animation': activeRankingIndex === 5 }">模考击败榜</text>
							<view class="info-text left-align">模考数据源自大家，请贡献力量，填写模考复盘</view>
						</view>
					</view>
					<view class="ranking-list">
						<view class="ranking-item" v-for="(item, index) in (showAllExamDefeatRankings ? examDefeatRankings : examDefeatRankings.slice(0,3))" :key="item.userid" @click="navigateToPersonal(item.userid)">
							<view class="rank-number" :class="[
								index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : '',
								item.userid === user.userId ? 'current-user' : ''
							]">{{ index + 1 }}</view>
							<view class="rank-info-container">
								<view class="rank-username exam-defeat-username" :class="{ 'current-user': item.userid === user.userId }">{{ item.user_nickname }}</view>
								<view class="rank-details">
									<text class="detail-item">次数：{{ item.examCount }}</text>
									<text class="detail-item">均分：{{ item.avgScore.toFixed(1) }}</text>
									<text class="detail-item beat-rate">击败率：{{ (item.avgBeatRate).toFixed(1) }}%</text>
								</view>
							</view>
						</view>
						<view class="toggle-ranking" @click="showAllExamDefeatRankings = !showAllExamDefeatRankings" v-if="examDefeatRankings.length > 3">
							<text>{{ showAllExamDefeatRankings ? '收起' : '查看全部' }}</text>
							<u-icon :name="showAllExamDefeatRankings ? 'arrow-up' : 'arrow-down'" color="#666666" size="14"></u-icon>
						</view>
					</view>
				</view>

				<!-- 学习时长排行榜 -->
				<view class="ranking-section">
					<view class="ranking-header">
						<view class="ranking-title-section">
							<view class="ranking-header-row">
								<text class="ranking-title" :class="{ 'star-animation': activeRankingIndex === 1 }">学习时长榜</text>
								<!-- 身份类型标签 -->
								<view class="identity-tabs">
									<view class="identity-tab-item" :class="{ 'active': isStudyTimeIdentityTabActive('在职') }" @click="switchStudyTimeIdentityTab('在职')">
										在职
									</view>
									<view class="identity-tab-item" :class="{ 'active': isStudyTimeIdentityTabActive('全职') }" @click="switchStudyTimeIdentityTab('全职')">
										全职
									</view>
									<view class="identity-tab-item" :class="{ 'active': isStudyTimeIdentityTabActive('应届') }" @click="switchStudyTimeIdentityTab('应届')">
										应届
									</view>
								</view>
							</view>
							<!-- 排行榜标签切换 -->
							<view class="ranking-tabs">
								<view class="tab-item" :class="{ 'active': currentStudyTimeTab === tab }" @click="switchStudyTimeTab(tab)" v-for="tab in ['dayStudyTime','weekStudyTime','monthStudyTime','totalStudyTime']" :key="tab">
									{{ tab === 'dayStudyTime' ? '日榜' : tab === 'weekStudyTime' ? '周榜' : tab === 'monthStudyTime' ? '月榜' : '总榜' }}
								</view>
							</view>
						</view>
					</view>
					<view class="ranking-list">
						<view class="ranking-item" v-for="(item, index) in (showAllStudyTimeRankings ? studyTimeRankings : studyTimeRankings.slice(0,3))" :key="item.userId">
							<view class="rank-number" :class="[
								index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : '',
								item.userId === user.userId ? 'current-user' : ''
							]">{{ index + 1 }}</view>
							<view class="rank-username" :class="{ 'current-user': item.user_id === user.userId }">{{ item.userNickname }}</view>
							<view class="rank-score" :class="{ 'current-user': item.user_id === user.userId }">{{ item.study_duration}}h</view>
						</view>
						<view class="toggle-ranking" @click="showAllStudyTimeRankings = !showAllStudyTimeRankings" v-if="studyTimeRankings.length > 3">
							<text>{{ showAllStudyTimeRankings ? '收起' : '查看全部' }}</text>
							<u-icon :name="showAllStudyTimeRankings ? 'arrow-up' : 'arrow-down'" color="#666666" size="14"></u-icon>
						</view>
					</view>
				</view>

				<!-- 刷题量排行榜 -->
				<view class="ranking-section">
					<view class="ranking-header">
						<view class="ranking-title-section">
							<view class="ranking-header-row">
								<text class="ranking-title" :class="{ 'star-animation': activeRankingIndex === 2 }">刷题数量榜</text>
								<!-- 身份类型标签 -->
								<view class="identity-tabs">
									<view class="identity-tab-item" :class="{ 'active': isQuestionIdentityTabActive('在职') }" @click="switchQuestionIdentityTab('在职')">
										在职
									</view>
									<view class="identity-tab-item" :class="{ 'active': isQuestionIdentityTabActive('全职') }" @click="switchQuestionIdentityTab('全职')">
										全职
									</view>
									<view class="identity-tab-item" :class="{ 'active': isQuestionIdentityTabActive('应届') }" @click="switchQuestionIdentityTab('应届')">
										应届
									</view>
								</view>
							</view>
							<!-- 排行榜标签切换 -->
							<view class="ranking-tabs">
								<view class="tab-item" :class="{ 'active': currentQuestionTab === tab }" @click="switchQuestionTab(tab)" v-for="tab in ['dayQuestion','weekQuestion','monthQuestion','totalQuestion']" :key="tab">
									{{ tab === 'dayQuestion' ? '日榜' : tab === 'weekQuestion' ? '周榜' : tab === 'monthQuestion' ? '月榜' : '总榜' }}
								</view>
							</view>
						</view>
					</view>
					<view class="ranking-list">
						<view class="ranking-item" v-for="(item, index) in (showAllQuestionRankings ? questionRankings : questionRankings.slice(0,3))" :key="item.userId">
							<view class="rank-number" :class="[
								index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : '',
								item.userId === user.userId ? 'current-user' : ''
							]">{{ index + 1 }}</view>
							<view class="rank-username" :class="{ 'current-user': item.user_id === user.userId }">{{ item.userNickname }}</view>
							<view class="rank-score" :class="{ 'current-user': item.user_id === user.userId }">{{ formatNumber(item.question_count) }}题</view>
						</view>
						<view class="toggle-ranking" @click="showAllQuestionRankings = !showAllQuestionRankings" v-if="questionRankings.length > 3">
							<text>{{ showAllQuestionRankings ? '收起' : '查看全部' }}</text>
							<u-icon :name="showAllQuestionRankings ? 'arrow-up' : 'arrow-down'" color="#666666" size="14"></u-icon>
						</view>
					</view>
				</view>
				
				<!-- 资料一表通算榜 -->
				<view class="ranking-section">
					<view class="ranking-header">
						<view class="ranking-title-section">
							<text class="ranking-title" :class="{ 'star-animation': activeRankingIndex === 3 }">一表通算榜</text>
							<view class="info-text left-align">本功能模仿自【行测小助手】</view>
						</view>
					</view>
					<view class="ranking-list">
						<view class="ranking-item" v-for="(item, index) in (showAllTableRankings ? tableRankings : tableRankings.slice(0,3))" :key="item.id">
							<view class="rank-number" :class="[
								index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : '',
								item.userId === user.userId ? 'current-user' : ''
							]">{{ index + 1 }}</view>
							<view class="rank-info-container">
								<view class="rank-username" :class="{ 'current-user': item.userId === user.userId }">{{ item.userName }}</view>
								<view class="rank-score" :class="{ 'current-user': item.userId === user.userId }">{{ item.modeBest}}分</view>
								<view class="rank-time" :class="{ 'current-user': item.userId === user.userId }">{{ formatDateTime(item.createTime) }}</view>							
							</view>
						</view>
						<view class="toggle-ranking" @click="showAllTableRankings = !showAllTableRankings" v-if="tableRankings.length > 3">
							<text>{{ showAllTableRankings ? '收起' : '查看全部' }}</text>
							<u-icon :name="showAllTableRankings ? 'arrow-up' : 'arrow-down'" color="#666666" size="14"></u-icon>
						</view>
					</view>
				</view>

				<!-- 算力排行榜 -->
			<view class="ranking-section">
				<view class="ranking-header">
					<view class="ranking-title-section">
						<text class="ranking-title" :class="{ 'star-animation': activeRankingIndex === 4 }">基础计算榜</text>
						<!-- 横向滑动的标签容器 -->
						<view class="horizontal-tabs-container">
							<scroll-view class="horizontal-tabs-scroll" scroll-x="true" show-scrollbar="false" :scroll-with-animation="true">
								<view class="ranking-tabs horizontal-tabs">
									<view class="tab-item" :class="{ 'active': currentComputeTab === mode.type }" @click="switchComputeTab(mode.type)" v-for="mode in computeModes" :key="mode.type">
										{{ mode.title }}
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
				</view>
				<view class="ranking-list">
					<view class="ranking-item" v-for="(item, index) in (showAllComputeRankings ? computeRankings : computeRankings.slice(0,3))" :key="item.id">
						<view class="rank-number" :class="[
							index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : '',
							item.userId === user.userId ? 'current-user' : ''
						]">{{ index + 1 }}</view>
						<view class="rank-info-container">
							<view class="rank-username" :class="{ 'current-user': item.userId === user.userId }">{{ item.userName }}</view>
							<view class="rank-score" :class="{ 'current-user': item.userId === user.userId }">{{ formatTime(item.totalTime) }}</view>
							<view class="rank-time" :class="{ 'current-user': item.userId === user.userId }">{{ formatDateTime(item.createTime) }}</view>							
						</view>
					</view>
					<view class="toggle-ranking" @click="showAllComputeRankings = !showAllComputeRankings" v-if="computeRankings.length > 3">
						<text>{{ showAllComputeRankings ? '收起' : '查看全部' }}</text>
						<u-icon :name="showAllComputeRankings ? 'arrow-up' : 'arrow-down'" color="#666666" size="14"></u-icon>
					</view>
				</view>
			</view>

			</view>
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex';
	import { noticeList, rankingInfo, estimateRecordList, groupExamStatistics } from "@/config/api.js";
	import uIcon from '@/uni_modules/uview-ui/components/u-icon/u-icon.vue';

	// 功能模块配置
	const MODULE_CONFIG = [
		[
			{ key: 'experience', title: '上岸经验', icon: 'account-fill', color: '#4A89DC' },
			{ key: 'job-filter', title: '岗位筛选', icon: 'list', color: '#FFA500' },
			{ key: 'calculation', title: '资料速算', icon: 'integral-fill', color: '#FF6B6B' },
			{ key: 'shenlun', title: '申论答案', icon: 'clock-fill', color: '#6C5CE7' }
		],
		[
			{ key: 'review', title: '模考复盘', icon: 'list-dot', color: '#ED5565' },
			{ key: 'original', title: '苏榜原创', icon: 'edit-pen-fill', color: '#5D9CEC' },
			{ key: 'pk-battle', title: 'PK对决', icon: 'gift', color: '#FF6B6B' }
		]
	];

	// 页面路由配置
	const ROUTE_MAP = {
		experience: '/pages/articles/index?channelId=0',
		original: '/pages/articles/index?channelId=5',
		'job-filter': '/pages/job-filter/index',
		calculation: '/pages/calculation/index',
		shenlun: '/pages/papers/provinceList',
		review: '/pages/review/index',
		focus: '/pages/focus/index',
		mark: '/pages/mark/index',
		'pk-battle': '/pages/pk-battle/index'
	};

	export default {
		components: { uIcon },
		data() {
				return {
					title: '苏榜',
					showAnnouncement: false,
					noticeData: {},
					// 日期和倒计时
					currentDate: '',
					daysToExam: 0,
					// 排行榜数据
					punchRankings: [],
					studyTimeRankings: [],
					questionRankings: [],
					// 展开状态
					showAllPunchRankings: false,
					showAllStudyTimeRankings: false,
					showAllQuestionRankings: false,
					// 当前选中的标签
					currentPunchTab: 'monthTotalMark',
					currentStudyTimeTab: 'dayStudyTime',
					currentQuestionTab: 'dayQuestion',
					currentComputeTab: 'twoDigitAddSub',
					// 身份类型标签
					currentPunchIdentityTab: '',
					currentStudyTimeIdentityTab: '',
					currentQuestionIdentityTab: '',
					// 算力排行榜相关数据
					computeRankings: [],
					showAllComputeRankings: false,
					computeModes: [
						{ title: '两位数加减', type: 'twoDigitAddSub' },
						{ title: '三位数加减', type: 'threeDigitAddSub' },
						{ title: '20以内分化百', type: 'fractionToPercentage' },
						{ title: '三位数乘1.1', type: 'threeDigitMultiply1_1' },
						{ title: '三位数乘0.9', type: 'threeDigitMultiply0_9' },
						{ title: '两位数相乘', type: 'twoDigitMultiply' },
						{ title: '两位数乘一位数', type: 'twoDigitOneDigitMultiply' },
						{ title: '三位数除一位数', type: 'threeDigitOneDigitDivide' }
					],
					// 资料一表通算榜相关数据
					tableRankings: [],
					showAllTableRankings: false,
					// 模考击败榜相关数据
					examDefeatRankings: [],
					showAllExamDefeatRankings: false,
					// 功能区不需要再展开/收起，默认为显示
					// 星星闪烁效果相关
					activeRankingIndex: -1, // 当前闪烁的排行榜索引
					rankingTitles: ['每日打卡榜', '学习时长榜', '刷题数量榜', '一表通算榜', '基础计算榜', '模考击败榜'] // 排行榜标题数组
				}
		},
		onLoad() {
			uni.$on('loginSuccess', this.initPage);
			this.loginSuccess && this.initPage();
			
			// 初始化日期和倒计时
			this.updateDateAndCountdown();
			// 每天更新一次
			this.countdownTimer = setInterval(this.updateDateAndCountdown, 86400000);
		},
		onUnload() {
			// 清除定时器
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
			// 清除星星闪烁定时器
			if (this.starAnimationTimer) {
				clearInterval(this.starAnimationTimer);
			}
		},
		computed: {
			...mapState(['user', 'loginSuccess']),
			allModules() {
				// 将所有功能模块合并为一个数组
				return MODULE_CONFIG.flat();
			}
		},
		onShareAppMessage() {
			return {
				title: '苏榜带你上上分！',
				imageUrl: "../../static/img/share.jpg",
				path: '/pages/index/index'
			};
		},
		methods: {
			async initPage() {
				const { statusBarHeight } = await uni.getWindowInfo();
				this.statusBarHeight = statusBarHeight || 20;

				// 计算公告栏底部位置
				this.$nextTick(() => {
					this.calculateAnnouncementPosition();
				});

				Promise.all([
					this.getNoticeData(),
					this.getPunchRankings(),
						this.getStudyTimeRankings(),
						this.getQuestionRankings(),
						this.getComputeRankings(),
						this.getTableRankings(),
						this.getExamDefeatRankings()
					]).catch(err => console.error('初始化数据失败:', err));
				
				// 启动星星闪烁效果
				this.startStarAnimation();
			},
			
			// 启动星星闪烁动画
			startStarAnimation() {
				// 每5秒切换到下一个排行榜标题
				this.starAnimationTimer = setInterval(() => {
					this.activeRankingIndex = (this.activeRankingIndex + 1) % this.rankingTitles.length;
				}, 5000);
			},
			
			// 更新日期和倒计时
			updateDateAndCountdown() {
				const now = new Date();
				
				// 格式化当前日期 (例如: 2023年10月15日 星期日)
				const year = now.getFullYear();
				const month = now.getMonth() + 1;
				const day = now.getDate();
				const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
				const weekday = weekdays[now.getDay()];
				this.currentDate = `${year}年${month}月${day}日 ${weekday}`;
				
				// 计算距离12月7日的天数
				const examDate = new Date(year, 11, 7); // 月份从0开始，11表示12月
				
				// 如果今年的考试日期已过，则计算明年的
				if (now > examDate) {
					examDate.setFullYear(year + 1);
				}
				
				// 计算天数差
				const timeDiff = examDate - now;
				this.daysToExam = Math.ceil(timeDiff / (1000 * 3600 * 24));
			},

			async getNoticeData() {
				uni.showLoading({ title: '加载中' });
				try {
					const { code, rows } = await noticeList();
					if (code === 200 && rows?.length) this.noticeData = rows[0];
				} catch (err) {
					console.error('获取公告失败:', err);
				} finally {
					uni.hideLoading();
				}
			},

			async getPunchRankings() {
				try {
					let params = `?rankType=${this.currentPunchTab}`;
					// 如果选择了身份类型，添加到参数中
					if (this.currentPunchIdentityTab) {
						params += `&identityTab=${this.currentPunchIdentityTab}`;
					}
					const { code, data } = await rankingInfo(params);
					if (code === 200 && data) {
						this.punchRankings = data
							.filter(item => item.total_mark_count != null)
							.sort((a, b) => b.total_mark_count - a.total_mark_count);
					}
				} catch (err) {
					console.error('获取打卡排行榜失败:', err);
				}
			},

			async getStudyTimeRankings() {
				try {
					let params = `?rankType=${this.currentStudyTimeTab}`;
					// 如果选择了身份类型，添加到参数中
					if (this.currentStudyTimeIdentityTab) {
						params += `&identityTab=${this.currentStudyTimeIdentityTab}`;
					}
					const { code, data } = await rankingInfo(params);
					if (code === 200 && data) {
						this.studyTimeRankings = data
							.filter(item => item.study_duration != null)
							.sort((a, b) => b.study_duration - a.study_duration);
					}
				} catch (err) {
					console.error('获取学习时长排行榜失败:', err);
				}
			},

			async getQuestionRankings() {
				try {
					let params = `?rankType=${this.currentQuestionTab}`;
					// 如果选择了身份类型，添加到参数中
					if (this.currentQuestionIdentityTab) {
						params += `&identityTab=${this.currentQuestionIdentityTab}`;
					}
					const { code, data } = await rankingInfo(params);
					if (code === 200 && data) {
						this.questionRankings = data
							.filter(item => item.question_count != null)
							.sort((a, b) => b.question_count - a.question_count);
					}
				} catch (err) {
					console.error('获取刷题量排行榜失败:', err);
				}
			},

			async getComputeRankings() {
				try {
					const params = `?pageNum=1&pageSize=20&modeType=${this.currentComputeTab}`;
					const { code, rows } = await estimateRecordList(params);
					if (code === 200 && rows) {
						// 按用时排序（从小到大），用时越少排名越高
						this.computeRankings = rows
							.filter(item => item.totalTime != null)
							.sort((a, b) => a.totalTime - b.totalTime);
					}
				} catch (err) {
					console.error('获取算力排行榜失败:', err);
				}
			},

			// 获取资料一表通算榜数据
			async getTableRankings() {
				try {
					const params = `?pageNum=1&pageSize=20&modeType=table-analysis`;
					const { code, rows } = await estimateRecordList(params);
					if (code === 200 && rows) {
						// 按modeBest降序排列，分数越高排名越高
						this.tableRankings = rows
							.filter(item => item.modeBest != null)
							.sort((a, b) => b.modeBest - a.modeBest);
					}
				} catch (err) {
					console.error('获取资料一表通算榜失败:', err);
				}
			},

			switchPunchTab(tabType) {
				if (this.currentPunchTab === tabType) return;
				this.currentPunchTab = tabType;
				this.showAllPunchRankings = false;
				this.getPunchRankings();
			},

			switchStudyTimeTab(tabType) {
				if (this.currentStudyTimeTab === tabType) return;
				this.currentStudyTimeTab = tabType;
				this.showAllStudyTimeRankings = false;
				this.getStudyTimeRankings();
			},

			switchQuestionTab(tabType) {
				if (this.currentQuestionTab === tabType) return;
				this.currentQuestionTab = tabType;
				this.showAllQuestionRankings = false;
				this.getQuestionRankings();
			},

				switchPunchIdentityTab(tabType) {
					// 中文到英文的映射
					const identityMap = {
						'在职': 'workingProfessional',
						'全职': 'fullTimeStudent', 
						'应届': 'graduateStudent'
					};
					
					if (this.currentPunchIdentityTab === identityMap[tabType]) {
						// 如果点击已选中的标签，取消选中
						this.currentPunchIdentityTab = '';
					} else {
						// 选中新标签，传递英文参数
						this.currentPunchIdentityTab = identityMap[tabType];
					}
					this.showAllPunchRankings = false;
					this.getPunchRankings();
				},

			switchStudyTimeIdentityTab(tabType) {
				// 中文到英文的映射
				const identityMap = {
					'在职': 'workingProfessional',
					'全职': 'fullTimeStudent', 
					'应届': 'graduateStudent'
				};
				
				if (this.currentStudyTimeIdentityTab === identityMap[tabType]) {
					// 如果点击已选中的标签，取消选中
					this.currentStudyTimeIdentityTab = '';
				} else {
					// 选中新标签，传递英文参数
					this.currentStudyTimeIdentityTab = identityMap[tabType];
				}
				this.showAllStudyTimeRankings = false;
				this.getStudyTimeRankings();
			},

			switchQuestionIdentityTab(tabType) {
				// 中文到英文的映射
				const identityMap = {
					'在职': 'workingProfessional',
					'全职': 'fullTimeStudent', 
					'应届': 'graduateStudent'
				};
				
				if (this.currentQuestionIdentityTab === identityMap[tabType]) {
					// 如果点击已选中的标签，取消选中
					this.currentQuestionIdentityTab = '';
				} else {
					// 选中新标签，传递英文参数
					this.currentQuestionIdentityTab = identityMap[tabType];
				}
				this.showAllQuestionRankings = false;
				this.getQuestionRankings();
			},

			// 切换算力榜选项卡
			switchComputeTab(tabType) {
				if (this.currentComputeTab === tabType) return;
				this.currentComputeTab = tabType;
				this.showAllComputeRankings = false;
				this.getComputeRankings();
			},

			// 获取模考击败榜数据
				async getExamDefeatRankings() {
					try {
						// 获取用户所在的小组ID，如果没有则使用默认值
						const user = uni.getStorageSync('user') || {};
						// 这里假设我们使用默认的小组ID，实际应用中应该获取用户所属的小组
						const defaultGroupId = '8b2500e3a5a14ab3b6f7690ea625120a'; // 默认小组ID
						const res = await groupExamStatistics(defaultGroupId);
						if (res && res.data) {
							// 按击败率排序（从高到低）
							this.examDefeatRankings = res.data
								.filter(item => item.avgBeatRate != null)
								// 映射字段名，确保与模板中使用的一致
								.map(item => ({
									...item,
									userId: item.userid,      // 将userid映射到userId
									userNickname: item.user_nickname // 将user_nickname映射到userNickname
								}))
								.sort((a, b) => b.avgBeatRate - a.avgBeatRate);
						}
					} catch (error) {
						console.error('获取模考击败榜数据失败：', error);
					}
				},

			// 跳转到个人页面（需要消耗积分）
			navigateToPersonal(userId) {
				// 检查积分是否充足（阅读需要2积分）
				if ((this.user.totalPoints || 0) < 2) {
					uni.$u.toast('您的积分不足，无法查看模考（需要2积分）');
					return;
				}
				
				uni.showModal({
					title: '查看提示',
					content: '查看用户模考信息需要消耗2积分，是否继续？',
					success: (res) => {
						if (res.confirm) {
							// 用户确认后跳转到个人页面
							uni.navigateTo({
								url: '/pages/review/personal?userid=' + userId
							});
						}
					}
				});
			},

			toggleAnnouncement() {
				this.showAnnouncement = !this.showAnnouncement;
				// 公告栏状态变化后重新计算位置
				this.$nextTick(() => {
					this.calculateAnnouncementPosition();
				});
			},

			navigateTo(moduleKey) {
				// 特殊处理PK对决模块，显示开发中提示
				if (moduleKey === 'pk-battle') {
					uni.showModal({
						title: '功能提示',
						content: '该功能还在开发中……',
						showCancel: false
					});
					return;
				}
				
				const url = ROUTE_MAP[moduleKey];
				if (url) uni.navigateTo({ url });
				else console.log('未知模块:', moduleKey);
			},

			calculateAnnouncementPosition() {
				// 在小程序环境中不需要设置CSS变量
				// 移除了对document的直接操作，避免在非Web环境中报错
			},



			formatNumber(num = 0) {
				return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
			},

			formatTime(seconds) {
				const minutes = Math.floor(seconds / 60);
				const secs = seconds % 60;
				return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
			},
			
			// 格式化日期时间
			formatDateTime(dateString) {
				if (!dateString) return '';
				
				// 兼容 iOS 的日期格式处理
				let formattedDateString = dateString;
				// 如果是 "yyyy-MM-dd HH:mm:ss" 格式，转换为 iOS 兼容格式
				if (dateString.includes('-') && dateString.includes(' ') && dateString.includes(':')) {
					formattedDateString = dateString.replace(' ', 'T');
				}
				// 如果只是 "yyyy-MM-dd" 格式，保持不变（iOS 支持）
				
				const date = new Date(formattedDateString);
				
				// 检查日期是否有效
				if (isNaN(date.getTime())) {
					console.warn('Invalid date format:', dateString);
					return dateString; // 返回原始字符串
				}
				
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 判断身份标签是否选中的辅助方法
			isPunchIdentityTabActive(chineseTab) {
				const identityMap = {
					'在职': 'workingProfessional',
					'全职': 'fullTimeStudent', 
					'应届': 'graduateStudent'
				};
				return this.currentPunchIdentityTab === identityMap[chineseTab];
			},

			isStudyTimeIdentityTabActive(chineseTab) {
				const identityMap = {
					'在职': 'workingProfessional',
					'全职': 'fullTimeStudent', 
					'应届': 'graduateStudent'
				};
				return this.currentStudyTimeIdentityTab === identityMap[chineseTab];
			},

			isQuestionIdentityTabActive(chineseTab) {
				const identityMap = {
					'在职': 'workingProfessional',
					'全职': 'fullTimeStudent', 
					'应届': 'graduateStudent'
				};
				return this.currentQuestionIdentityTab === identityMap[chineseTab];
			}
		}
	}
</script>

<style>
	/* 全局容器 */
	.view-contain {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #f8f8f8;
		min-height: 100vh;
		padding-bottom: calc(env(safe-area-inset-bottom) + 60px); /* 留出底部导航栏空间 */
		box-sizing: border-box;
	}

	/* 日期和倒计时区域 */
	.date-countdown-container {
		width: 88%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 0;
	}
	.current-date {
		font-size: 15px;
		color: #333;
	}
	.exam-countdown {
		display: flex;
		align-items: center;
	}
	.countdown-label {
		font-size: 14px;
		color: #666;
		margin-right: 5px;
	}
	.countdown-value {
		font-size: 15px;
		font-weight: 600;
		color: #e74c3c;
	}

	/* 公告栏+打卡按钮容器 */
	.announcement-punch-container {
		width: 88%;
		display: flex;
		gap: 10px;
	}

	/* 公告栏 */
	.announcement-bar {
		flex: 5;
		background-color: #f5f5f5;
		border-radius: 10px;
		padding: 12px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
	}
	.announcement-header {
		display: flex;
		align-items: center;
	}
	.announcement-icon {
		margin-right: 10px;
	}
	.announcement-title {
		flex: 1;
		font-size: 16px;
		font-weight: 500;
		color: #333;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	.announcement-content {
		margin-top: 12px;
		padding-top: 12px;
		border-top: 1px solid rgba(0, 0, 0, 0.05);
	}
	.announcement-text {
		font-size: 14px;
		color: #666;
		line-height: 1.5;
		width: 100%;
	}
	.announcement-text>>>p { margin: 5px 0; }
	.announcement-text>>>img { max-width: 100%; height: auto; }
	.announcement-text>>>a { color: #4A89DC; text-decoration: none; }
	.announcement-footer {
		display: flex;
		justify-content: flex-end;
		margin-top: 10px;
		font-size: 12px;
		color: #999;
	}

	/* 打卡按钮 */
	.punch-btn-container {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.punch-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 6px;
		padding: 10px 15px;
		border-radius: 25px;
		font-size: 14px;
		width: 120px;
		font-weight: 500;
		box-shadow: 0 4px 15px rgba(74, 137, 220, 0.3);
		transition: all 0.3s ease;
	}
	.punch-btn:active {
		transform: translateY(2px);
		box-shadow: 0 2px 8px rgba(74, 137, 220, 0.2);
	}
	.punch-icon {
		animation: pulse 2s infinite;
	}
	@keyframes pulse {
		0% { transform: scale(1); }
		50% { transform: scale(1.1); }
		100% { transform: scale(1); }
	}
	.punch-text {
		letter-spacing: 0.5px;
	}

	/* 主要内容区域（上下布局） */
	.main-content-container {
		width: 100%;
		display: flex;
		flex-direction: column;
		margin-top: 15px;
		padding: 0 2%;
		padding-bottom: calc(env(safe-area-inset-bottom) + 60px); /* 底部导航栏高度 */
		box-sizing: border-box;
		gap: 15px;
		min-height: calc(100vh - 200px); /* 确保内容区域占满屏幕 */
	}

	/* 顶部功能模块区域 */
	.modules-container {
		width: 100%;
		overflow: hidden;
	}

	/* 功能模块滚动容器 */
	.modules-scroll {
		width: 100%;
		white-space: nowrap;
	}

	/* 功能模块行布局 */
	.modules-row {
		display: inline-flex;
		gap: 12px;
	}

	/* 模块卡片（横排布局，一行四列） */
	.module-card {
		width: calc(25% - 9px); /* 25%宽度减去间距 */
		min-width: 80px;
		background-color: #fff;
		border-radius: 10px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
		min-height: 70px;
		transition: all 0.3s ease;
	}

	.module-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	.module-title {
		font-size: 12px;
		color: #333;
		margin-top: 8px;
		text-align: center;
		line-height: 1.3;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 100%;
	}

	.module-icon {
		margin-bottom: 5px;
	}

	/* 左侧排行榜区域（瀑布流） */
	.rankings-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 15px;
		overflow-y: auto;
	}

	/* 单个排行榜区域 */
	.ranking-section {
		background-color: #fff;
		border-radius: 12px;
		padding: 10px 15px 0;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
	}

	/* 排行榜通用样式 */
	.ranking-header {
		margin-bottom: 15px;
	}

	.ranking-title-section {
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	/* 排行榜标题行布局 */
	.ranking-header-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 5px;
	}

	/* 身份类型标签 */
	.identity-tabs {
		display: flex;
		gap: 6px;
		align-items: center;
	}

	.identity-tab-item {
		font-size: 11px;
		padding: 3px 6px;
		border-radius: 8px;
		color: #999;
		border: 1px solid #e0e0e0;
		background-color: #f9f9f9;
		min-width: 32px;
		text-align: center;
		transition: all 0.2s ease;
	}

	.identity-tab-item.active {
		background-color: #FF6B47;
		color: white;
		border-color: #FF6B47;
	}

	.ranking-title {
		font-size: 16px;
		font-weight: 600;
		color: #333;
		margin-bottom: 5px;
		position: relative;
		/* 专业稳重的深蓝色渐变 */
		background: linear-gradient(90deg, #1E40AF, #3B82F6, #1E40AF);
		background-size: 200% 200%;
		-webkit-background-clip: text;
		background-clip: text;
		-webkit-text-fill-color: transparent;
		/* 简洁的光晕效果 */
		animation: professional-glow 3s ease-in-out infinite;
	}

	/* 专业稳重的光晕动画 */
	@keyframes professional-glow {
		0% {
			background-position: 0% 50%;
			filter: brightness(1) saturate(1);
			text-shadow: 0 0 6px rgba(59, 130, 246, 0.3);
		}
		50% {
			background-position: 100% 50%;
			filter: brightness(1.1) saturate(1.2);
			text-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
		}
		100% {
			background-position: 0% 50%;
			filter: brightness(1) saturate(1);
			text-shadow: 0 0 6px rgba(59, 130, 246, 0.3);
		}
	}

	.ranking-tabs {
		display: flex;
		gap: 8px;
		flex-wrap: wrap;
	}

	.tab-item {
		font-size: 12px;
		padding: 4px 8px;
		border-radius: 10px;
		color: #666;
		border: 1px solid #e0e0e0;
		background-color: #f9f9f9;
	}

	.tab-item.active {
		background-color: #4A89DC;
		color: white;
		border-color: #4A89DC;
	}

	.ranking-list {
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	.ranking-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.ranking-item:last-child {
		border-bottom: none;
	}

	.rank-number {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 13px;
		color: white;
	}

	.rank-number.first {
		background-color: #FFD700;
	}

	.rank-number.second {
		background-color: #C0C0C0;
	}

	.rank-number.third {
		background-color: #CD7F32;
	}

	.rank-number:not(.first):not(.second):not(.third) {
		background-color: #f0f0f0;
		color: #666;
	}

	.rank-info {
		flex: 1;
		margin: 0 10px;
		display: flex;
		flex-direction: column;
	}

	.rank-info-container {
		flex: 1;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 0 10px;
	}

	.rank-username {
		font-size: 14px;
		flex: 2; /* 用户名宽度增加，占用2份空间 */
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: none; /* 移除最大宽度限制 */
	}

	.rank-time {
		font-size: 12px;
		color: #999;
		flex: 1; /* 时间信息保持不变，占用1份空间 */
		text-align: center;
	}

	.rank-score {
		font-size: 14px;
		font-weight: 500;
		flex: 1; /* 得分信息保持不变，占用1份空间 */
		text-align: center;
	}

	.rank-username.current-user,
	.rank-time.current-user,
	.rank-score.current-user {
		color: #4A89DC;
	}

	.toggle-ranking {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 5px;
		font-size: 13px;
		color: #666;
		padding: 8px 0;
	}

	.module-card-hover {
		background-color: #f9f9f9;
	}

	/* 横向滑动标签样式 */
	.horizontal-tabs-container {
		width: 100%;
		overflow: hidden;
	}

	.horizontal-tabs-scroll {
		width: 100%;
		white-space: nowrap;
	}

	.horizontal-tabs {
		flex-wrap: nowrap;
		width: auto;
		padding-bottom: 5px;
		justify-content: flex-start;
	}

	.horizontal-tabs .tab-item {
		white-space: nowrap;
	}

	/* 排行榜标题红金动画效果 */
	@keyframes red-gold-glow {
		0% {
			background-position: 0% 50%;
			filter: brightness(1) saturate(1.2);
		}
		50% {
			background-position: 100% 50%;
			filter: brightness(1.3) saturate(1.6);
		}
		100% {
			background-position: 0% 50%;
			filter: brightness(1) saturate(1.2);
		}
	}

	@keyframes red-gold-sparkle {
		0%, 100% {
			text-shadow: 
				0 0 6px rgba(255, 215, 0, 0.9),
				0 0 12px rgba(255, 215, 0, 0.7),
				0 0 18px rgba(255, 215, 0, 0.5),
				0 0 24px rgba(255, 215, 0, 0.3);
		}
		50% {
			text-shadow: 
				0 0 6px rgba(220, 20, 60, 0.9),
				0 0 12px rgba(220, 20, 60, 0.7),
				0 0 18px rgba(220, 20, 60, 0.5),
				0 0 24px rgba(220, 20, 60, 0.3);
		}
	}
	
	/* 星星闪烁动画 */
	@keyframes star-animation {
		0% {
			text-shadow: 
				0 0 6px rgba(255, 215, 0, 0.9),
				0 0 12px rgba(255, 215, 0, 0.7),
				0 0 18px rgba(255, 215, 0, 0.5),
				0 0 24px rgba(255, 215, 0, 0.3);
		}
		25% {
			text-shadow: 
				0 0 8px rgba(255, 255, 255, 0.9),
				0 0 16px rgba(255, 255, 255, 0.7),
				0 0 24px rgba(255, 255, 255, 0.5);
		}
		50% {
			text-shadow: 
				0 0 6px rgba(220, 20, 60, 0.9),
				0 0 12px rgba(220, 20, 60, 0.7),
				0 0 18px rgba(220, 20, 60, 0.5),
				0 0 24px rgba(220, 20, 60, 0.3);
		}
		75% {
			text-shadow: 
				0 0 8px rgba(255, 255, 255, 0.9),
				0 0 16px rgba(255, 255, 255, 0.7),
				0 0 24px rgba(255, 255, 255, 0.5);
		}
		100% {
			text-shadow: 
				0 0 6px rgba(255, 215, 0, 0.9),
				0 0 12px rgba(255, 215, 0, 0.7),
				0 0 18px rgba(255, 215, 0, 0.5),
				0 0 24px rgba(255, 215, 0, 0.3);
		}
	}
	
	.star-animation {
		animation: star-animation 2s linear infinite;
	}

	/* 鼠标悬停时增强发光效果 */
	.ranking-title:hover {
		animation-duration: 1.5s;
		transform: scale(1.05);
		transition: transform 0.3s ease;
		filter: brightness(1.4) saturate(1.8);
	}

	/* 新增小文字说明样式 */
	.info-text {
		font-size: 12px;
		color: #666;
	}
	
	.info-text.left-align {
		text-align: left;
	}
	
	/* 模考击败榜详情样式 */
	.rank-details {
		display: flex;
		flex-direction: column;
		flex: 1;
	}
	
	.detail-item {
		font-size: 12px;
		color: #666;
		margin: 2px 0;
		display: block;
	}
	
	.beat-rate {
		color: #e74c3c; /* 击败率使用醒目颜色 */
		font-weight: 500;
	}
	
	/* 模考击败榜用户名超链接样式 */
	.exam-defeat-username {
		color: #4A89DC; /* 蓝色，通常表示可点击 */
		text-decoration: underline;
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.exam-defeat-username:hover {
		color: #357ABD; /* 悬停时颜色加深 */
		text-decoration: underline;
		transform: scale(1.02);
	}
	
	.exam-defeat-username.current-user {
		color: #4A89DC !important; /* 确保当前用户也使用链接颜色 */
		text-decoration: underline;
	}
</style>
